﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using StockWeb;


using System.Runtime.InteropServices;
using System.IO;
using System.Xml;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Net;


namespace StocSmartDevice
{
    public partial class frmStock : Form
    {
        private StockWebSerivce stocws;
        private DataTable dtProd;
        private int iPageCount;
        private int iMaxRec;
        private int iPageSize;
        private int iCurrentPage;
        private int iRecNo;
        const int iDefaultPAging = 6;
        ImageButton btnFiltreazaPic = null, btnFiltreazaPicStoc = null, btnBack = null, btnBack01 = null, btnForward = null, btnForward01 = null, btnResetFiltru = null ;

        public frmStock()
        {
            InitializeComponent();
            stocws = new StockWebSerivce();
            stocws.Url = "http://192.168.1.2/StockWebService/StockWebSerivce.asmx";
            stocws.Timeout = -1;

            btnFiltreazaPic = new ImageButton();
            btnFiltreazaPic.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.refresh.png"));
            btnFiltreazaPic.Location = new Point(picTop.Location.X + picTop.Width / 2 - btnFiltreazaPic.Width , picTop.Location.Y + picTop.Height - 25); //new Point(97,240);
            btnFiltreazaPic.Size =  new Size(24,24);
            btnFiltreazaPic.Click += new EventHandler(btnFiltreazaPic_click);
            this.Controls.Add(btnFiltreazaPic);
            btnFiltreazaPic.BringToFront();

            btnFiltreazaPicStoc = new ImageButton();
            btnFiltreazaPicStoc.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.refresh.png"));
            btnFiltreazaPicStoc.Location = new Point(203, 5);
            btnFiltreazaPicStoc.Size = new Size(24, 24);
            btnFiltreazaPicStoc.Click += new EventHandler(btnFiltreazaPicStoc_click);
            this.Controls.Add(btnFiltreazaPicStoc);
            btnFiltreazaPicStoc.BringToFront();

            btnResetFiltru = new ImageButton();
            btnResetFiltru.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.Repeat_01.png"));
            btnResetFiltru.Location = new Point(203, 32);
            btnResetFiltru.Size = new Size(24, 24);
            btnResetFiltru.Click += new EventHandler(btnResetFiltru_click);
            this.Controls.Add(btnResetFiltru);
            btnResetFiltru.BringToFront();

            btnBack = new ImageButton();
            btnBack.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.Backward.png"));
            btnBack.Location = new Point(39, 240);
            btnBack.Size = new Size(24, 24);
            btnBack.Click += new EventHandler(btnBack_click);
            this.Controls.Add(btnBack);
            btnBack.BringToFront();

            btnBack01 = new ImageButton();
            btnBack01.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.Backward_01.png"));
            btnBack01.Location = new Point(3, 240);
            btnBack01.Size = new Size(24, 24);
            btnBack01.Click += new EventHandler(btnBack01_click);
            this.Controls.Add(btnBack01);
            btnBack01.BringToFront();

            btnForward = new ImageButton();
            btnForward.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.Forward.png"));
            btnForward.Location = new Point(76, 240);
            btnForward.Size = new Size(24, 24);
            btnForward.Click += new EventHandler(btnForward_click);
            this.Controls.Add(btnForward);
            btnForward.BringToFront();

            btnForward01 = new ImageButton();
            btnForward01.Image = new System.Drawing.Bitmap(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("StocSmartDevice.Forward_01.png"));
            btnForward01.Location = new Point(112, 240);
            btnForward01.Size = new Size(24, 24);
            btnForward01.Click += new EventHandler(btnForward01_click);
            this.Controls.Add(btnForward01);
            btnForward01.BringToFront();
        }

        private void btnFiltreazaPic_click(object sender, EventArgs e)
        {
           /* dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 0);
            Filtreaza();*/

            dateProd.CustomFormat = "dd/MM/yyyy";
            dtProd = stocws.getTopProduse(dateProd.Text);
            dateProd.CustomFormat = "MMMM dd, yyyy - dddd";
            gridProduse.DataSource = dtProd;
        }

        private void btnFiltreazaPicStoc_click(object sender, EventArgs e)
        {
            dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 0);
            Filtreaza();
        }

        private void btnResetFiltru_click(object sender, EventArgs e)
        {
            txtCod.Text = txtDenum.Text = string.Empty;

            dtProd = stocws.getProduseStoc(string.Empty, string.Empty, 0);

            Filtreaza();
        }


        private void btnBack_click(object sender, EventArgs e)
        {
            if (iCurrentPage == iPageCount)
                iRecNo = iPageSize * (iCurrentPage - 2);

            iCurrentPage = iCurrentPage - 1;


            if (iCurrentPage < 1)
            {
                MessageBox.Show("Te afli deja pe prima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                iCurrentPage = 1;
                return;
            }
            else
                iRecNo = iPageSize * (iCurrentPage - 1);

            LoadPage();
        }
        private void btnBack01_click(object sender, EventArgs e)
        {
            if (iCurrentPage == 1)
            {
                MessageBox.Show("Te afli deja pe prima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }

            iCurrentPage = 1;
            iRecNo = 0;

            LoadPage();
        }
        private void btnForward_click(object sender, EventArgs e)
        {
            iCurrentPage = iCurrentPage + 1;

            if (iCurrentPage > iPageCount)
            {
                iCurrentPage = iPageCount;

                if (iRecNo == iMaxRec)
                {
                    MessageBox.Show("Te afli deja pe ultima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

            }

            LoadPage();
        }
        private void btnForward01_click(object sender, EventArgs e)
        {
            // Check if you are already at the last page.
            if (iRecNo == iMaxRec)
            {
                MessageBox.Show("Te afli deja pe ultima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }


            iCurrentPage = iPageCount;

            iRecNo = iPageSize * (iCurrentPage - 1);

            LoadPage();
        }
        

        private void btnAfiseaza_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 0);
          
            }
            catch (Exception ex)
            { }
        }

        private void request_iulia(string sLogFile)
        {
            WriteToLog(sLogFile, "request iulia");
            // Create a request for the URL. 		
            WebRequest request = WebRequest.Create("http://iulia-mobile/");
           // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            WriteToLog(sLogFile, "response1 " +  response.StatusDescription.ToString ());
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            WriteToLog(sLogFile, "response2 " + responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();


        }

        private void request_ip(string sLogFile)
        {
            WriteToLog(sLogFile, "request ip");
            // Create a request for the URL. 		
            WebRequest request = WebRequest.Create("http://192.168.1.2/");
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            WriteToLog(sLogFile, "response1 " + response.StatusDescription.ToString());
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            WriteToLog(sLogFile, "response2 " + responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();


        }

        private void setIp()
        {
            XmlTextReader textReader = new XmlTextReader(System.IO.Path.GetDirectoryName(
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\AppParams.xml");

            textReader.Read();
            string IP = string.Empty;

            // If the node has value

            XmlDocument doc = new XmlDocument();
            doc.Load(System.IO.Path.GetDirectoryName(
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\AppParams.xml");

            XmlNodeList elements = doc.GetElementsByTagName("connection");
            foreach (XmlNode element in elements)
            {
                IP = element.ChildNodes[0].InnerText ;
            }
           /* while (textReader.Read())
            {

                // Move to fist element

                textReader.MoveToElement();

                
                IP = textReader.Value.ToString();

            }*/

            stocws.Url = "http://" + IP + "//StockWebService//StockWebSerivce.asmx";

        }

        private void frmStock_Load(object sender, EventArgs e)
        {
            setIp();

            string sLogFile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).ToString() + "\\logfile.txt";
            
                // Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName).ToString() + "\\logfile.log" ;

            InitLog(sLogFile);
            try
            {
                request_iulia(sLogFile);
            }
            catch (Exception ex)
            {
                WriteToLog(sLogFile, ex.Message);
            }
            try
            {
                request_ip(sLogFile);
            }
            catch (Exception ex)
            {
                WriteToLog(sLogFile, ex.Message);
            }
            //WriteToLog(sLogFile, "load");

            try
            {

                dateProd.Value = Convert.ToDateTime("01/01/" + System.DateTime.Today.Year.ToString());
                dateProd.CustomFormat = "dd/MM/yyyy";
                
                dtProd = stocws.getTopProduse(dateProd.Text);
                dateProd.CustomFormat = "MMMM dd, yyyy - dddd";
                gridProduse.DataSource = dtProd;
                setVisibleControls(true);
            }
            catch (Exception ex)
            {
                WriteToLog(sLogFile, ex.Message);
            }
        }

        public void InitLog(string LogFile)
        {
            try
            {
                if (LogFile.Length > 0)
                {
                    StreamWriter sw = new StreamWriter(LogFile, false);
                    sw.WriteLine(); sw.WriteLine();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append('*', 80); sb.Append(Environment.NewLine);
                    sb.Append(' ', 80); sb.Append(Environment.NewLine);
                    sb.Append("STOC MENTOR, updated " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString());
                    sb.Append(Environment.NewLine);
                    sb.Append(' ', 80); sb.Append(Environment.NewLine);
                    sb.Append('*', 80); sb.Append(Environment.NewLine);
                    sw.WriteLine(sb.ToString());
                    sw.Flush(); sw.Close();
                }
            }
            catch { }
        }
        public void WriteToLog(string LogFile, string comment)
        {
            if (LogFile.Length > 0)
            {
                StreamWriter sw = new StreamWriter(LogFile, true);
                sw.WriteLine(comment);
                sw.Flush(); sw.Close();
            }
        }

        private void tabPrincipal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabPrincipal.SelectedIndex == 1)
            {
                setVisibleControls(false);

                dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 0);
                gridProdStoc.DataSource = dtProd;
                Filtreaza();
            }
            if (tabPrincipal.SelectedIndex == 0)
            {
                setVisibleControls(true);
            }
        }
        private void setVisibleControls(bool bVisible)
        {
            btnFiltreazaPic.Visible = bVisible;
            btnFiltreazaPic.Enabled = bVisible;
            lblTop.Visible = bVisible;

            btnFiltreazaPicStoc.Visible = !bVisible;
            btnFiltreazaPicStoc.Enabled = !bVisible;
            btnBack.Visible = !bVisible;
            btnBack.Enabled = !bVisible;
            btnBack01.Visible = !bVisible;
            btnBack01.Enabled = !bVisible;
            btnForward.Visible = !bVisible;
            btnForward01.Enabled = !bVisible;
            btnForward01.Visible = !bVisible;
            btnResetFiltru.Visible = !bVisible;
            btnResetFiltru.Enabled = !bVisible;
        }
        private void Filtreaza()
        {

            //Set the start and max records. 
            iPageSize = iDefaultPAging;

            iMaxRec = dtProd.Rows.Count;
            iPageCount = Convert.ToInt32(iMaxRec / iPageSize);

            // Adjust the page number if the last page contains a partial page.
            if ((iMaxRec % iPageSize) > 0)
                iPageCount = iPageCount + 1;


            //Initial seeings
            iCurrentPage = 1;
            iRecNo = 0;

            //Display the content of the current page.
            LoadPage();

        }

        private void LoadPage()
        {
            int i, iStartRec, iEndRec;
            DataTable dtTemp;
            DataRow dr;

            //Duplicate or clone the source table to create the temporary table.
            dtTemp = dtProd.Clone();

            if (iCurrentPage == iPageCount)
                iEndRec = iMaxRec;
            else
                iEndRec = iPageSize * iCurrentPage;

            iStartRec = iRecNo;

            //Copy the rows from the source table to fill the temporary table.
            if (dtProd.Rows.Count > 0)
                for (i = iStartRec; i <= iEndRec - 1; i++)
                {
                    dtTemp.ImportRow(dtProd.Rows[i]);
                    iRecNo = iRecNo + 1;
                }
            else dtTemp = null;
            gridProdStoc.DataSource = dtTemp;
            //DisplayPageInfo();
            lblPagina.Text = "Pagina  " + iCurrentPage.ToString() + " / " + iPageCount.ToString();

        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (iCurrentPage == 1)
            {
                MessageBox.Show("Te afli deja pe prima pagina!","", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1  );
                return;
            }

            iCurrentPage = 1;
            iRecNo = 0;

            LoadPage();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            // Check if you are already at the last page.
            if (iRecNo == iMaxRec)
            {
                MessageBox.Show("Te afli deja pe ultima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                return;
            }


            iCurrentPage = iPageCount;

            iRecNo = iPageSize * (iCurrentPage - 1);

            LoadPage();
        }

        private void btnSpate_Click(object sender, EventArgs e)
        {

            if (iCurrentPage == iPageCount)
                iRecNo = iPageSize * (iCurrentPage - 2);

            iCurrentPage = iCurrentPage - 1;


            if (iCurrentPage < 1)
            {
                MessageBox.Show("Te afli deja pe prima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                iCurrentPage = 1;
                return;
            }
            else
                iRecNo = iPageSize * (iCurrentPage - 1);

            LoadPage();

        }

        private void btnFata_Click(object sender, EventArgs e)
        {
            iCurrentPage = iCurrentPage + 1;

            if (iCurrentPage > iPageCount)
            {
                iCurrentPage = iPageCount;

                if (iRecNo == iMaxRec)
                {
                    MessageBox.Show("Te afli deja pe ultima pagina!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    return;
                }

            }

            LoadPage();
        }

        private void btnFiltreaza_Click(object sender, EventArgs e)
        {
            dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 0);
            Filtreaza();
        }

        private void btnFiltreaza1_Click(object sender, EventArgs e)
        {
            dateProd.CustomFormat = "dd/MM/yyyy";
            dtProd = stocws.getTopProduse(dateProd.Text );
            dateProd.CustomFormat = "MMMM dd, yyyy - dddd";
            gridProduse.DataSource = dtProd;
        }

        private void chkStoc_CheckStateChanged(object sender, EventArgs e)
        {
            if (chkStoc.Checked)
            {
                dtProd = stocws.getProduseStoc(txtDenum.Text, txtCod.Text, 1);
                
                //Filtreaza();
            }
        }

        private void btnResetFiltrus_Click(object sender, EventArgs e)
        {
            txtCod.Text = txtDenum.Text = string.Empty;

            dtProd = stocws.getProduseStoc(string.Empty, string.Empty, 0);

            Filtreaza();
        }

        private void picStoc_Paint(object sender, PaintEventArgs e)
        {
            /*Graphics gr = e.Graphics;
            Font fnt = new Font("Arial", 10, FontStyle.Bold );
            SolidBrush brush = new SolidBrush(Color.Black);
            gr.DrawString("Cod produs:", fnt, brush , picStoc.Left , picStoc.Top );
            gr.DrawString("Cod produssdsdsasjhdjasdjgasjgdjasgdjasgfjhgsfgjsfgj:", fnt, brush, picStoc.Left + picStoc.Width / 10, picStoc.Top - picStoc.Height / 10);*/

            DrawLabel(lblPagina, e.Graphics);
            DrawLabel(lblDenumire, e.Graphics);
            DrawLabel(lblCod, e.Graphics);
            DrawLabel(lblCheck, e.Graphics);
            
        }

        private void DrawLabel(Label label, Graphics grx)
        {

            if (label.TextAlign == ContentAlignment.TopLeft)
            {

                grx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), label.Bounds);
                
            }

            else if (label.TextAlign == ContentAlignment.TopCenter)
            {

                SizeF size = grx.MeasureString(label.Text, label.Font);

                int left = this.Width / 2 - (int)size.Width / 2;

                Rectangle rect = new Rectangle(left, label.Top, (int)size.Width, (int)label.Height);

                grx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);

            }

            else if (label.TextAlign == ContentAlignment.TopRight)
            {

                SizeF size = grx.MeasureString(label.Text, label.Font);

                int left = label.Width - (int)size.Width + label.Left;

                Rectangle rect = new Rectangle(left, label.Top, (int)size.Width, (int)size.Height);

                grx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);

            }

        }

        private void picProd_Paint(object sender, PaintEventArgs e)
        {
            
           
        }

        private void picTop_Paint(object sender, PaintEventArgs e)
        {
            DrawLabel(lblTop, e.Graphics);
        }
    }
}